import axios from 'axios'
import {
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'
import {
	getToken
} from '@/utils/auth'

// create an axios instance
const service = axios.create({
	baseURL: 'http://8.141.174.64:9527', // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000, // request timeout
})
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent


		// let each request carry token
		// ['X-Token'] is a custom headers key
		// please modify it according to the actual situation
		if (getToken()) {
			config.headers['Authorization'] = `Bearer ${getToken()}`
			// config.headers.token = `Bearer ${getToken()}`
			

		}

		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// 响应拦截器
service.interceptors.response.use(res => {
    const code = res.data.code
    if (code === 401) {
      MessageBox.confirm(
        '登录状态已过期，您可以继续留在该页面，或者重新登录',
        '系统提示',
        {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code !== 200) {
      Notification.error({
        title: res.data.msg
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export function get(url, params = {}) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
				params: params
			})
			.then(response => {
				resolve(response.data);
			})
			.catch(err => {
				reject(err)
			})
	})
}
export function post(url, data = {}) {
	return new Promise((resolve, reject) => {
		axios.post(url, qs.stringify(data))
			.then(response => {
				resolve(response.data);
			}, err => {
				reject(err)
			})
	})
}

export default service
